﻿using System;
using System.Globalization;
using System.IO;

namespace Project.Services.Tools
{
    public static class LogHelper
    {

        private static readonly object Locker = new object();
        /// <summary>
        /// 错误日志
        /// </summary>
        /// <param name="msg"></param>
        public static void WriteLog(this string msg)
        {
            lock (Locker)
            {
                string folder = DateTime.Now.ToString("yyyyMM");
                string newPath = AppDomain.CurrentDomain.BaseDirectory + "\\Log\\" + "\\" + folder + "\\";
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                string path = newPath + DateTime.Today.ToString("yyyyMMdd") + ".log";
                if (!File.Exists(path))
                {
                    File.Create(path).Close();
                }
                using (StreamWriter w = File.AppendText(path))
                {
                    w.WriteLine("\r\nLog Entry : ");
                    w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                    w.WriteLine(msg);
                    w.WriteLine("________________________________________________________");
                    w.Flush();
                    w.Close();
                }
            }
        }

        public static void ErrorHandle(this Exception ex)
        {
            string message =
                $"消息类型：{ex.GetType().Name}\r\n消息内容：{ex.Message}\r\n引发异常的方法：{ex.TargetSite}\r\n引发异常的对象：{ex.Source}\r\nStackTrace：{ex.StackTrace}\r\nInnerException：{ex.InnerException}";
            message.WriteLog();
        }
    }
}
